from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action

from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin
from rest_framework.response import Response
from rest_framework.permissions import AllowAny


from apps.spit.models import Spit
from apps.spit.serializers import SpitSerializer


class SpitViewSet(ModelViewSet):

    lookup_value_regex = '\d+'
    queryset = Spit.objects.all()
    serializer_class = SpitSerializer
    permission_classes = [AllowAny]

    def perform_authentication(self, request):
        try:
            super().perform_authentication(request)
        except Exception:
            pass

    # 获取所有一级吐槽 spit/
    def list(self, request):

        spitList = self.get_queryset().filter(parent=None).order_by("-publishtime")
        retSpitList = []

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spitList:
                flag_collect = redis_conn.hget("collect_%s" % user.id, str(spit.id))
                flag_thumbup = redis_conn.hget("thumbup_%s" % user.id, str(spit.id))
                if flag_collect:
                    spit.collected = True
                if flag_thumbup:
                    spit.hasthumbup = True

                retSpitList.append(spit)
        else:
            retSpitList = spitList

        s = self.get_serializer(instance=retSpitList, many=True)
        return Response(s.data)

    def create(self, request):

        data = request.data

        user = request.user
        if user.is_authenticated:
            data['userid'] = user.id
            data['nickname'] = user.nickname
            data['avatar'] = user.avatar

        # else:
        #     data['userid'] = None
        #     data['nickname'] = '匿名用户'
        #     data['avatar'] = None

        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            spit = serializer.save()

            if data.get('parent', None):
                spit.parent.comment += 1

            return Response(serializer.data)
        else:
            print(serializer.errors)
            return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

    @action(methods=['put'], detail=True, url_path='collect')
    def collect(self, request, pk):
        user = request.user

        spit = self.get_object()

        if not user.is_authenticated:
            return Response({'message': '请登录后重试'}, status=status.HTTP_401_UNAUTHORIZED)
        redis_conn = get_redis_connection('spit')
        spit_collected = redis_conn.hkeys('collect_%d' % user.id)
        spit_collected = [spit.decode() for spit in spit_collected]
        print(spit_collected)

        if pk in spit_collected:
            redis_conn.hdel('collect_%d' % user.id, pk)
            spit.save()
            return Response({"message": "取消收藏成功", "success": True})
        else:
            redis_conn.hset('collect_%d' % user.id, pk, 1)
            spit.save()
            return Response({"message": "收藏成功", "success": True})

    @action(methods=['put'], detail=True, url_path='updatethumbup')
    def updatethumbup(self, request, pk):
        user = request.user

        spit = Spit.objects.get(id=pk)

        if not user.is_authenticated:
            return Response({'message': '请登录后重试'}, status=status.HTTP_401_UNAUTHORIZED)
        redis_conn = get_redis_connection('spit')
        spit_thumbup = redis_conn.hkeys('thumbup_%d' % user.id)
        spit_thumbup = [spit.decode() for spit in spit_thumbup]
        print(spit_thumbup)

        if pk in spit_thumbup:
            redis_conn.hdel('thumbup_%d' % user.id, pk)
            spit.thumbup -= 1
            spit.save()
            return Response({"message": "取消点赞成功", "success": True})
        else:
            redis_conn.hset('thumbup_%d' % user.id, pk, 1)
            spit.thumbup += 1
            spit.save()
            return Response({"message": "点赞成功", "success": True})

    def retrieve(self, request, pk):
        spit = self.get_object()
        spit.visits += 1
        spit.save()
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            flag_collect = redis_conn.hget("collect_%d" % user.id, pk)
            flag_thumbup = redis_conn.hget("thumbup_%d" % user.id, pk)
            if flag_collect:
                spit.collected = True
            if flag_thumbup:
                spit.hasthumbup = True

        s = self.get_serializer(instance=spit)
        return Response(s.data)

    # 获取吐槽的评论  spit/{pk}/children/
    @action(methods=["GET"], detail=True, url_path="children")
    def get_children(self, request, pk):

        spitList = self.get_queryset().filter(parent=pk).order_by("-publishtime")
        retSpitList = []

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spitList:
                flag_collect = redis_conn.hget("collect_%s" % user.id, str(spit.id))
                flag_thumbup = redis_conn.hget("thumbup_%s" % user.id, str(spit.id))
                if flag_collect:
                    spit.collected = True
                if flag_thumbup:
                    spit.hasthumbup = True

                retSpitList.append(spit)
        else:
            retSpitList = spitList

        s = self.get_serializer(instance=retSpitList, many=True)
        return Response(s.data)


